import socket               # Import socket module
import select
import time
import threading
from Tkinter import Text

class connectAndSend(threading.Thread):
    def __init__(self, gs, txt, i, scroll):
        threading.Thread.__init__(self)
        self.gameState = gs
        self.text = txt
        self.info = i
        self.scrollbar = scroll
    def run(self):
	s = [socket.socket()]         # Create a socket object


	address = ''
	
	self.text.config(state = 'normal')
	self.text.insert('end', "\nEnter ip:")
	self.text.config(state = 'disabled')
	
	while self.gameState[0] == 0:
	    time.sleep(.005)
        
        address = self.info[0]

	port = 0

	self.text.config(state = 'normal')
	self.text.insert('end', "\nEnter port:")
	self.text.config(state = 'disabled')
	
	while self.gameState[0] == 1:
	    time.sleep(.0055)
	    
	port = self.info[1]    

	hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(address) # Get local machine name
	empty = []

	s[0].connect((hostname, port))
        
        
	receivedData = s[0].recv(4096)

	self.text.config(state = 'normal')
	self.text.insert('end', receivedData)
	self.text.config(state = 'disabled')

	readThread = readMessages(s, self.text, self.info, self.scrollbar)
	readThread.start()

	while True:
	    read_ready, write_ready, errors = select.select(s, s, empty, 5000)
	    for server in write_ready:
		if self.info[2]:
		    if self.info[3][:6] == "/disco":
		        s[0].shutdown(socket.SHUT_RDWR)
		        #s[0].close()
		        readThread.join()
		        return
		        
		    server.send(self.info[3])
		    self.info[2] = False



	s.close()                     # Close the socket when done

class readMessages(threading.Thread):
    def __init__(self, server, txt, i, scroll):
        threading.Thread.__init__(self)
        self.s = server
        self.text = txt
        self.info = i
        self.scrollbar = scroll
    def run(self):
        empty = []
        while True: 
            if self.info[3][:6] == "/disco":
                return
                
            read_ready, write_ready, errors = select.select(self.s, self.s, empty, 5000)
            for server in read_ready:
                msgreceived = server.recv(4096)
                self.text.config(state = 'normal')
		self.text.insert('end', "\n" + msgreceived)
                self.text.config(state = 'disabled')
                if float(self.scrollbar.get()[1]) > .99:
                    self.text.yview("moveto", 1)
    